<template>
  <el-form ref="form"
           :rules="rules"
           :model="form"
           label-width="80px">
    <div class="arc">
      <div class="arc-left">
        <el-card class="box-card t30"
                 shadow="never">
          <div slot="header"
               class="clearfix">
            <span>内容列表</span>
            <el-button style="float: right; padding: 3px 0"
                       type="text">添加文章</el-button>
          </div>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="标题："
                            prop="title">
                <el-input v-model="form.title"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="小标题：">
                <el-input class=""
                          v-model="form.shorttitle"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="点击：">
                <el-input-number controls-position="right"
                                 :step="10"
                                 v-model="form.click"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="属性：">
            <el-checkbox-group v-model="form.flag"
                               size="small">
              <el-checkbox-button v-for="item in flags"
                                  :label="item.att"
                                  :disabled="item.attname === '跳转'"
                                  :key="item.att">{{item.attname}}</el-checkbox-button>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item class="img-litpic"
                        label="略缩图：">
            <div class="demo-image__preview"
                 v-if="form.litpic">
              <el-image fit="fit"
                        :src="form.picname"
                        class="avatar"
                        :preview-src-list="[form.picname]">
              </el-image>
            </div>
            <el-input type="text"
                      class="img-input"
                      v-model="form.picname">
            </el-input>
            <el-upload class="avatar-uploader"
                       :action="imguploadurl"
                       :show-file-list="false"
                       :on-success="handleAvatarSuccess"
                       :before-upload="beforeAvatarUpload">

              <el-button class="img-up"
                         type="primary">上传<i class="el-icon-upload el-icon--right"></i></el-button>
            </el-upload>

          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item prop="typeid"
                            label="栏目：">
                <el-cascader v-model="form.typeid"
                             :options="children"
                             :props="{ expandTrigger: 'hover',checkStrictly :true }"
                             @change="handleChange"></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="10"
                    class="el-fly">
              <el-form-item label="副栏目：">
                <el-cascader clearable
                             v-model="form.typeid2"
                             :options="children"
                             :props="{ expandTrigger: 'hover', multiple: true,checkStrictly :true }"
                             @change="handleChange"></el-cascader>
              </el-form-item>
            </el-col>
          </el-row>

          <field ref='addfield'
                 v-if="addfields && dede_addonfieldval"
                 :addfields="addfields"
                 :dede_addonfieldval="dede_addonfieldval"></field>
          <editor v-if="form.body"
                  :catchData="form.body"></editor>
          <input type='hidden'
                 name='dede_addonfieldsss'
                 value="">
          <el-form-item>
            <input type='hidden'
                   name='dede_addonfields'
                   value="form.dede_addonfields">
            <el-button type="primary"
                       @click="submitForm('form')">立即创建</el-button>
            <el-button @click="resetForm('form')">重置</el-button>
          </el-form-item>

        </el-card>
      </div>
      <div class="arc-right">
        <el-card class="box-card t30"
                 shadow="never">
          <div slot="header"
               class="clearfix">
            <span>SEO</span>

          </div>
          <el-form label-position='top'>

            <el-form-item class="arc-tag"
                          label="TAG(关键字)：">
              <el-tag :key="tag"
                      v-for="tag in form.tags"
                      closable
                      :disable-transitions="false"
                      @close="handleClose(tag)">
                {{tag}}
              </el-tag>
              <el-input class="xh-input-80"
                        v-if="inputVisible"
                        v-model="inputValue"
                        ref="saveTagInput"
                        size="small"
                        @keyup.enter.native="handleInputConfirm"
                        @blur="handleInputConfirm">
              </el-input>
              <el-button v-else
                         class="button-new-tag"
                         size="small"
                         @click="showInput">+ New Tag</el-button>
            </el-form-item>
            <el-form-item label="描述：">
              <el-input type="textarea"
                        maxlength="250"
                        rows="4"
                        v-model="form.description"
                        placeholder="请输入内容"></el-input>
            </el-form-item>
            <el-form-item label="是否静态化（请勿动）：">
              <el-switch v-model="form.ishtml"
                         active-value="1"
                         active-text="静态"
                         inactive-text="动态"
                         inactive-value="0"
                         active-color="#13ce66">
              </el-switch>
            </el-form-item>

          </el-form>

        </el-card>
      </div>
    </div>
  </el-form>
</template>

<script>
import { arcaddajax, arcaddajaxData } from '../../axios/api'
import urls from '../../axios/url'
import editor from '../../components/editor/wangeditor'
import field from '../../components/addfield/addfield'
export default {
  components: { editor, field },
  data () {
    return {
      imguploadurl: urls.imgupload,
      inputVisible: false,
      inputValue: '',
      addfields: '',
      children: [],
      flags: [],
      dede_addonfieldval: '',
      form: {
        dopost: 'save',
        channelid: '',
        title: '测试',
        shorttitle: '测试',
        click: '',
        flag: [],
        tags: ['sg', '哈哈'],
        picname: '',
        typeid: '8',
        typeid2: '',
        description: '',
        keywords: '',
        color: '',
        pubdate: '',
        ishtml: '1',
        dede_addonfields: ''
      },
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          { min: 1, max: 30, message: '长度在 1 到 30 个字符', trigger: 'blur' }
        ],
        typeid: [
          { required: true, message: '请选择栏目', trigger: 'blur' }
        ]
      },
      notifications: []
    }
  },
  computed: {

  },
  mounted () {
    this.form.channelid = this.$route.params.id
    this.loaddata()
  },
  methods: {
    loaddata () {
      arcaddajax(this.form.channelid).then((res) => {
        if (res.data.state === 1) {
          this.addfields = res.data.data.addfield
          this.form.dede_addonfields = res.data.data.dede_addonfields
          this.dede_addonfieldval = res.data.data.dede_addonfieldval
          this.children = res.data.data.children
          this.flags = res.data.data.flags
        }
      })
    },
    handleAvatarSuccess (res, file) {
      if (res.state === 1) {
        this.$msg(res.msg, 1)
        this.form.picname = res.data
        // this.form.litpic = URL.createObjectURL(file.raw)
      } else {
        this.$msg(res.msg, 3)
      }
    },
    beforeAvatarUpload (file) {
      console.log(file)
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 1

      if (!isJPG) {
        this.$message.error('略缩图图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 1MB!')
      }
      return isJPG && isLt2M
    },
    handleChange (value) {
      console.log(value)
    },
    handleClose (tag) { // 关键字与tag
      this.form.tags.splice(this.form.tags.indexOf(tag), 1)
    },
    showInput () {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm () { // 添加关键字与tag
      let inputValue = this.inputValue
      if (inputValue) {
        this.form.tags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    getData () {
      return this.form
    },
    openmsg (item) {
      setTimeout(() => {
        let notify = this.$notify({
          title: item.tit + '：',
          message: '违禁字【' + item.data + '】',
          duration: 0,
          type: 'error'
        })
        this.notifications[item.field] = notify
      }, 0)
    },
    closemsg () {
      let _this = this
      for (let key in _this.notifications) {
        _this.notifications[key].close()
        delete _this.notifications[key]
      }
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    submitForm (formName) {
      const formaddfield = new Promise((resolve, reject) => {
        return this.$refs['addfield'].$refs['fieldaddfield'].validate((valid) => {
          if (valid) {
            resolve(this.$refs['addfield'].getData())
          } else {
            console.log('失败')
          }
        })
      })
      const thisform = new Promise((resolve, reject) => {
        return this.$refs[formName].validate((valid) => {
          if (valid) {
            resolve(this.getData())
          }
        })
      })
      Promise.all([formaddfield, thisform]).then((res) => {
        const addfieldData = this.$refs['addfield'].getData()
        const thisData = this.getData()
        const reqData = Object.assign(addfieldData, thisData)
        console.log(reqData)
        if (reqData) {
          arcaddajaxData(reqData).then((res) => {
            if (res.data.state === 1) {
              this.$msg(res.data.msg)
            } else if (res.data.state === 10) {
              const Datas = res.data.data

              this.$msg(res.data.msg)
              this.closemsg()
              // this.tcs.close()
              for (let item of Datas) {
                this.openmsg(item)
              }
            } else {
              this.$msg(res.data.msg)
            }
          })
        }
      })
    }

  },
  beforeRouteUpdate (to, from, next) {
    this.form.channelid = to.params.id // 模型id
    this.loaddata() // 根据this.zoneId，请求不同数据
    next()
  },
  watch: {
    'form.litpic': function (data) {
      if (data) {
        this.form.flag.push('p')
      }
    }
  }
}
</script>
<style lang='less' scoped>
.is-disabled + .el-cascader-node__label {
  color: #fff;
  cursor: not-allowed;
}
@import url("../../assets/css/arc.less");
</style>
